package com.crm.api.controller;

import com.crm.api.common.Result;
import com.crm.api.entity.WorkOrder;
import com.crm.api.service.WorkOrderService;
import com.crm.api.service.WorkOrderHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工单控制器
 */
@Slf4j
@RestController
@RequestMapping("/work-orders")
public class WorkOrderController {

    @Autowired
    private WorkOrderService workOrderService;

    @Autowired
    private WorkOrderHistoryService workOrderHistoryService;

    /**
     * 获取工单列表
     */
    @GetMapping
    public Result<Map<String, Object>> getWorkOrders(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String orderType,
            @RequestParam(required = false) String priority,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) Integer customerId,
            @RequestParam(required = false) Integer businessId,
            @RequestParam(required = false) Integer assignedTo,
            @RequestParam(required = false) Integer createdBy) {
        
        log.info("获取工单列表: page={}, size={}, title={}, status={}", 
                page, size, title, status);
        
        Map<String, Object> result = workOrderService.getWorkOrders(
                page, size, title, orderType, priority, status, 
                customerId, businessId, assignedTo, createdBy);
        
        return Result.success(result);
    }

    /**
     * 获取我的工单
     */
    @GetMapping("/my")
    public Result<Map<String, Object>> getMyWorkOrders(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String orderType,
            @RequestParam(required = false) String priority,
            @RequestParam(required = false) String status) {
        
        // 获取当前用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        log.info("获取我的工单列表: username={}, page={}, size={}", username, page, size);
        
        Map<String, Object> result = workOrderService.getMyWorkOrders(
                username, page, size, title, orderType, priority, status);
        
        return Result.success(result);
    }

    /**
     * 获取工单详情
     */
    @GetMapping("/{id}")
    public Result<Map<String, Object>> getWorkOrder(@PathVariable Integer id) {
        log.info("获取工单详情: id={}", id);
        
        Map<String, Object> workOrderDetail = workOrderService.getWorkOrderDetailById(id);
        if (workOrderDetail == null) {
            return Result.error(404, "工单不存在");
        }
        
        return Result.success(workOrderDetail);
    }

    /**
     * 创建工单
     */
    @PostMapping
    public Result<WorkOrder> createWorkOrder(@Valid @RequestBody WorkOrder workOrder) {
        // 获取当前用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        log.info("创建工单: title={}, creator={}", workOrder.getTitle(), username);
        
        WorkOrder createdWorkOrder = workOrderService.createWorkOrder(workOrder, username);
        return Result.success(createdWorkOrder);
    }

    /**
     * 更新工单
     */
    @PutMapping("/{id}")
    public Result<WorkOrder> updateWorkOrder(@PathVariable Integer id, @Valid @RequestBody WorkOrder workOrder) {
        log.info("更新工单: id={}, title={}", id, workOrder.getTitle());
        
        workOrder.setId(id);
        WorkOrder updatedWorkOrder = workOrderService.updateWorkOrder(workOrder);
        
        if (updatedWorkOrder == null) {
            return Result.error(404, "工单不存在");
        }
        
        return Result.success(updatedWorkOrder);
    }

    /**
     * 删除工单
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteWorkOrder(@PathVariable Integer id) {
        log.info("删除工单: id={}", id);
        
        boolean deleted = workOrderService.deleteWorkOrder(id);
        if (!deleted) {
            return Result.error(404, "工单不存在");
        }
        
        return Result.success();
    }

    /**
     * 分配工单
     */
    @PatchMapping("/{id}/assign")
    public Result<Void> assignWorkOrder(@PathVariable Integer id, @RequestBody Map<String, Integer> request) {
        Integer assignedTo = request.get("assignedTo");
        log.info("分配工单: id={}, assignedTo={}", id, assignedTo);
        
        boolean updated = workOrderService.assignWorkOrder(id, assignedTo);
        if (!updated) {
            return Result.error(404, "工单不存在");
        }
        
        return Result.success();
    }

    /**
     * 更新工单状态
     */
    @PatchMapping("/{id}/status")
    public Result<Void> updateWorkOrderStatus(@PathVariable Integer id, @RequestBody Map<String, String> request) {
        String status = request.get("status");
        log.info("更新工单状态: id={}, status={}", id, status);
        
        boolean updated = workOrderService.updateWorkOrderStatus(id, status);
        if (!updated) {
            return Result.error(404, "工单不存在");
        }
        
        return Result.success();
    }

    /**
     * 添加解决方案
     */
    @PatchMapping("/{id}/solution")
    public Result<Void> addWorkOrderSolution(@PathVariable Integer id, @RequestBody Map<String, String> request) {
        String solution = request.get("solution");
        
        // 获取当前用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        log.info("添加工单解决方案: id={}, operator={}", id, username);
        
        boolean updated = workOrderService.updateWorkOrderSolution(id, solution, username);
        if (!updated) {
            return Result.error(404, "工单不存在");
        }
        
        return Result.success();
    }

    /**
     * 添加客户反馈
     */
    @PatchMapping("/{id}/feedback")
    public Result<Void> addCustomerFeedback(@PathVariable Integer id, @RequestBody Map<String, Object> request) {
        String customerFeedback = (String) request.get("customerFeedback");
        Integer satisfactionRating = (Integer) request.get("satisfactionRating");
        log.info("添加客户反馈: id={}, satisfactionRating={}", id, satisfactionRating);
        
        boolean updated = workOrderService.updateCustomerFeedback(id, customerFeedback, satisfactionRating);
        if (!updated) {
            return Result.error(404, "工单不存在");
        }
        
        return Result.success();
    }

    /**
     * 完成工单
     */
    @PatchMapping("/{id}/complete")
    public Result<Void> completeWorkOrder(@PathVariable Integer id) {
        log.info("完成工单: id={}", id);
        
        boolean updated = workOrderService.completeWorkOrder(id);
        if (!updated) {
            return Result.error(404, "工单不存在或状态不允许完成");
        }
        
        return Result.success();
    }

    /**
     * 关闭工单
     */
    @PatchMapping("/{id}/close")
    public Result<Void> closeWorkOrder(@PathVariable Integer id) {
        log.info("关闭工单: id={}", id);
        
        boolean updated = workOrderService.closeWorkOrder(id);
        if (!updated) {
            return Result.error(404, "工单不存在");
        }
        
        return Result.success();
    }

    /**
     * 获取工单统计信息
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getWorkOrderStats(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String orderType,
            @RequestParam(required = false) Integer assignedTo) {
        
        log.info("获取工单统计信息: startDate={}, endDate={}, orderType={}", 
                startDate, endDate, orderType);
        
        Map<String, Object> stats = workOrderService.getWorkOrderStats(startDate, endDate, orderType, assignedTo);
        return Result.success(stats);
    }

    /**
     * 获取工单处理记录列表
     */
    @GetMapping("/{id}/solutions")
    public Result<List<Map<String, Object>>> getWorkOrderSolutions(@PathVariable Integer id) {
        log.info("获取工单处理记录: id={}", id);
        
        List<Map<String, Object>> solutions = workOrderHistoryService.getWorkOrderSolutions(id);
        return Result.success(solutions);
    }

    /**
     * 获取工单状态历史记录
     */
    @GetMapping("/{id}/status-history")
    public Result<List<Map<String, Object>>> getWorkOrderStatusHistory(@PathVariable Integer id) {
        log.info("获取工单状态历史: id={}", id);
        
        List<Map<String, Object>> statusHistory = workOrderHistoryService.getWorkOrderStatusHistory(id);
        return Result.success(statusHistory);
    }
}